<?php
/**
 * class Table implement basic CRUD action
 * 
 */
class Table extends Object
{
    //name of table's fields
    private  $_fieldList = null;
    /**
     * 
     */
    private  $_rules = null;
    /**
     * vd : $_rules = array(
     *                  'pk' => array('id',..),
     *                  'pk_auto_increment' => TRUE
     *                  'onInsert' => array(''),
     *                  'onSelect' => '*',
     *
     *                      )
     */

    //protected $_input_data = null;
    //protected $_query_condition;
    
    
    function  __construct($tableName,$dataArray = NULL)
    {
//        $table = get_called_class();
        $this->_rules['tableName'] = $tableName;
        
        if (isset($dataArray))
        foreach($dataArray as $key => $value)
            $this->set($key, $value);
    }

    public function insert($dataArray = NULL)
    {        
        if(is_null($dataArray))
        {
            if(is_null($this->_fieldList))
                exit('No insertion data found !');
            $dataArray =& $this->_fieldList;
        }
        $db = DataProvider::getInstance();
        $db->insert($this->_rules['tableName'],$dataArray);
        
    }

    public function get($condition = NULL,$optionArray = NULL)
    {
        $db = DataProvider::getInstance();
        if(!isset($optionArray['order']))
            $optionArray['order'] = NULL;
        if(!isset($optionArray['limit']))
            $optionArray['limit'] = 10000;
        if(!isset($optionArray['offset']))
            $optionArray['offset'] = 0;
        return $db->get($this->_rules['tableName'],$condition,$optionArray['order'],$optionArray['limit'],$optionArray['offset']);
    }

    public function update($condition = NULL, $dataArray = NULL)
    {
        if(is_null($dataArray))
        {
            if(is_null($this->_fieldList))
                exit('No update data found !');
            $dataArray =& $this->_fieldList;
        }
        $db = DataProvider::getInstance();
        $db->update($this->_rules['tableName'],$dataArray,$condition);
    }

    public function remove($condition = NULL)
    {
        $db = DataProvider::getInstance();
        $db->remove($this->_rules['tableName'],$condition);
    }

    //getter & setter
    public function setField(&$arrayOfField)
    {
        $this->_fieldList =& $arrayOfField;
    }
    
    public function set($fieldName, $data)
    {
        foreach($this->_fieldList as $key => $value)
        {
            if ($key==$fieldName)
                $this->_fieldList["$fieldName"] = $data;
        }
    }
    
    /*public function get($fieldName)
    {
        return $this->_fieldList["$fieldName"];
    }*/

    public function check()
    {
        if(sizeof($this->_fieldList) == 0)
                exit("Table has to have at least 1 field !");
    }
    
    public function inserted_id()
    {
        $db = DataProvider::getInstance();
        return $db->inserted_id();
    }
}

?>